package com.framework.beans.factory.xml;

import com.framework.beans.BeanDefinition;
import com.framework.beans.MutablePropertyValues;
import com.framework.beans.PropertyValue;
import com.framework.beans.factory.support.BeanDefinitionReader;
import com.framework.beans.factory.support.BeanDefinitionRegistry;
import com.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.transform.sax.SAXResult;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.List;

// 解析xml文件
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    // 注册表对象
    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        this.registry = new SimpleBeanDefinitionRegistry();
    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    // 使用 dom4j 进行 xml配置解析
    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {

        // 获取 输入流
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocation);
        SAXReader reader = new SAXReader();
        Document document = reader.read(is);
        // 根标签对象 (beans)
        Element rootElement = document.getRootElement();
        // 解析 所有bean标签
        parsebean(rootElement);
    }

    // 解析bean标签
    private void parsebean(Element rootElement) {
        List<Element> elements = rootElement.elements();
        // 遍历Bean标签
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String className = element.attributeValue("class");
            // 封装Bean的对象
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);
            // 遍历获取 所有property标签
            List<Element> propertyList = element.elements("property");
            // Bean对象的所有 property
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            for (Element element1 : propertyList) {
                String name = element1.attributeValue("name");
                String ref = element1.attributeValue("ref");
                String value = element1.attributeValue("value");
                mutablePropertyValues.addPropertyValue(new PropertyValue(name , ref , value));
            }
            beanDefinition.setPropertyValues(mutablePropertyValues);
            // 注册对象
            registry.registerBeanDefinition(id, beanDefinition);
        }
    }



}
